import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { BottomNavigation } from "@/components/ui/bottom-navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Calendar,
  ChevronLeft,
  ChevronRight,
  Grid3X3,
  ChevronDown,
  Expand,
  Minimize,
  Share,
} from "lucide-react";

const monthlyTimelineData = [
  {
    month: "2024年1月",
    days: [
      {
        date: "2024-01-15",
        day: "15",
        dayOfWeek: "周一",
        events: [
          {
            time: "08:00",
            title: "早餐",
            photos: 5,
            location: "酒店",
            thumbnail:
              "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
          },
          {
            time: "09:00",
            title: "故宫博物院",
            photos: 25,
            location: "北京",
            thumbnail:
              "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
          },
          {
            time: "11:30",
            title: "太和殿",
            photos: 12,
            location: "故宫",
            thumbnail:
              "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
          },
          {
            time: "12:30",
            title: "御花园",
            photos: 18,
            location: "故宫",
            thumbnail:
              "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
          },
          {
            time: "14:30",
            title: "午餐时光",
            photos: 8,
            location: "王府井",
            thumbnail:
              "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
          },
          {
            time: "16:00",
            title: "王府井大街",
            photos: 15,
            location: "王府井",
            thumbnail:
              "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
          },
          {
            time: "17:30",
            title: "小吃街",
            photos: 22,
            location: "王府井",
            thumbnail:
              "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
          },
          {
            time: "19:00",
            title: "晚餐",
            photos: 11,
            location: "烤鸭店",
            thumbnail:
              "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
          },
          {
            time: "20:30",
            title: "夜景拍摄",
            photos: 28,
            location: "天安门",
            thumbnail:
              "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
          },
          {
            time: "21:45",
            title: "夜市逛街",
            photos: 16,
            location: "前门",
            thumbnail:
              "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
          },
          {
            time: "22:30",
            title: "酒吧小憩",
            photos: 7,
            location: "三里屯",
            thumbnail:
              "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
          },
        ],
      },
      {
        date: "2024-01-14",
        day: "14",
        dayOfWeek: "周日",
        events: [
          {
            time: "10:00",
            title: "天安门广场",
            photos: 18,
            location: "北京",
            thumbnail:
              "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
          },
          {
            time: "16:00",
            title: "下午茶",
            photos: 12,
            location: "三里屯",
            thumbnail:
              "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
          },
        ],
      },
      {
        date: "2024-01-13",
        day: "13",
        dayOfWeek: "周六",
        events: [
          {
            time: "08:30",
            title: "颐和园",
            photos: 32,
            location: "北京",
            thumbnail:
              "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
          },
        ],
      },
    ],
  },
  {
    month: "2023年12月",
    days: [
      {
        date: "2023-12-25",
        day: "25",
        dayOfWeek: "周一",
        events: [
          {
            time: "10:00",
            title: "浅草寺",
            photos: 31,
            location: "东京",
            thumbnail:
              "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
          },
          {
            time: "15:30",
            title: "传统街区",
            photos: 16,
            location: "浅草",
            thumbnail:
              "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
          },
        ],
      },
      {
        date: "2023-12-23",
        day: "23",
        dayOfWeek: "周六",
        events: [
          {
            time: "11:00",
            title: "东京塔",
            photos: 24,
            location: "东京",
            thumbnail:
              "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
          },
        ],
      },
    ],
  },
];

export default function Timeline() {
  const navigate = useNavigate();
  const [expandedMonths, setExpandedMonths] = useState<Set<string>>(
    new Set(["2024年1月"]),
  );
  const [expandedDays, setExpandedDays] = useState<Set<string>>(new Set());
  const [allExpanded, setAllExpanded] = useState(false);

  const MAX_VISIBLE_CARDS = 4; // Maximum cards to show in horizontal scroll

  // Helper function to generate event IDs for navigation
  const getEventId = (title: string) => {
    const titleMap: { [key: string]: string } = {
      早餐: "breakfast",
      故宫博物院: "forbidden-city",
      太和殿: "hall-of-supreme-harmony",
      御花园: "imperial-garden",
      午餐时光: "lunch-time",
      王府井大街: "wangfujing-street",
      小吃街: "snack-street",
      晚餐: "dinner",
      夜景拍摄: "night-photography",
      夜市逛街: "night-market",
      酒吧小憩: "bar-rest",
      天安门广场: "tiananmen-square",
      下午茶: "afternoon-tea",
      颐和园: "summer-palace",
      浅草寺: "senso-ji",
      传统街区: "traditional-district",
      东京塔: "tokyo-tower",
    };
    return titleMap[title] || title.toLowerCase().replace(/\s+/g, "-");
  };

  const toggleDay = (dayKey: string) => {
    setExpandedDays((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(dayKey)) {
        newSet.delete(dayKey);
      } else {
        newSet.add(dayKey);
      }
      return newSet;
    });
  };

  const toggleMonth = (month: string) => {
    setExpandedMonths((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(month)) {
        newSet.delete(month);
      } else {
        newSet.add(month);
      }
      return newSet;
    });
  };

  const toggleAllMonths = () => {
    if (allExpanded) {
      setExpandedMonths(new Set());
      setAllExpanded(false);
    } else {
      setExpandedMonths(new Set(monthlyTimelineData.map((data) => data.month)));
      setAllExpanded(true);
    }
  };

  const publishToSocialMedia = (type: "month" | "day", data: any) => {
    // Store the generated content in localStorage for the social media page
    const socialMediaPost = {
      id: Date.now().toString(),
      type: type,
      source: "timeline",
      title:
        type === "month"
          ? `${data.month}的美好回忆`
          : `${data.month}${data.day}日的精彩时光`,
      generatedAt: new Date().toISOString(),
      data: data,
    };

    localStorage.setItem("latestSocialPost", JSON.stringify(socialMediaPost));
    navigate("/social");
  };

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* Header */}
      <header className="sticky top-0 z-40 bg-background/80 backdrop-blur-lg border-b border-border">
        <div className="flex items-center justify-between p-4">
          <div>
            <h1 className="text-2xl font-bold text-foreground">时间轴</h1>
            <p className="text-sm text-muted-foreground">按时间回顾您的回忆</p>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={toggleAllMonths}>
              {allExpanded ? (
                <>
                  <Minimize className="h-4 w-4 mr-2" />
                  全部收��
                </>
              ) : (
                <>
                  <Expand className="h-4 w-4 mr-2" />
                  全部展开
                </>
              )}
            </Button>
            <Button variant="outline" size="sm">
              <Grid3X3 className="h-4 w-4 mr-2" />
              月视图
            </Button>
          </div>
        </div>
      </header>

      {/* Timeline Content */}
      <div className="space-y-0">
        {monthlyTimelineData.map((monthData, monthIndex) => {
          const isExpanded = expandedMonths.has(monthData.month);

          return (
            <div key={monthData.month}>
              {/* Month Header Bar - Sticky */}
              <div
                className="sticky top-16 z-30 bg-photo-50 border-b border-border py-4 px-4 cursor-pointer hover:bg-photo-100 transition-colors"
                onClick={() => toggleMonth(monthData.month)}
              >
                <div className="flex items-center justify-between">
                  <h2 className="text-xl font-semibold text-foreground">
                    {monthData.month}
                  </h2>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        publishToSocialMedia("month", monthData);
                      }}
                      className="text-xs"
                    >
                      <Share className="h-3 w-3 mr-1" />
                      发布社媒
                    </Button>
                    {isExpanded ? (
                      <ChevronDown className="h-5 w-5 text-muted-foreground" />
                    ) : (
                      <ChevronRight className="h-5 w-5 text-muted-foreground" />
                    )}
                  </div>
                </div>
              </div>

              {/* Days */}
              {isExpanded && (
                <div className="space-y-4 p-4">
                  {monthData.days.map((dayData, dayIndex) => {
                    const dayKey = `${monthData.month}-${dayData.date}`;
                    const isDayExpanded = expandedDays.has(dayKey);
                    const hasMoreEvents =
                      dayData.events.length > MAX_VISIBLE_CARDS;
                    const visibleEvents = isDayExpanded
                      ? dayData.events
                      : dayData.events.slice(0, MAX_VISIBLE_CARDS);

                    return (
                      <div key={dayData.date} className="space-y-3">
                        <div className="flex gap-4">
                          {/* Date Section */}
                          <div className="flex-shrink-0 w-20 text-center">
                            <div className="text-2xl font-bold text-foreground">
                              {dayData.day}日
                            </div>
                            <div className="text-sm text-muted-foreground">
                              {dayData.dayOfWeek}
                            </div>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() =>
                                publishToSocialMedia("day", {
                                  ...dayData,
                                  month: monthData.month,
                                })
                              }
                              className="text-xs mt-1 p-1 h-6"
                            >
                              <Share className="h-3 w-3 mr-1" />
                              发布
                            </Button>
                          </div>

                          {/* Events Cards - Horizontal Scroll or Grid */}
                          <div className="flex-1">
                            {isDayExpanded ? (
                              // Grid Layout for Expanded View
                              <div className="space-y-3">
                                <div className="flex flex-wrap gap-3">
                                  {dayData.events.map((event, eventIndex) => (
                                    <Card
                                      key={eventIndex}
                                      className="w-40 hover:shadow-md transition-shadow cursor-pointer"
                                      onClick={() =>
                                        navigate(
                                          `/event/${getEventId(event.title)}`,
                                        )
                                      }
                                    >
                                      <CardContent className="p-3">
                                        {/* Event Image with Watermarks */}
                                        <div className="relative w-full h-20 rounded-lg overflow-hidden mb-2">
                                          <img
                                            src={event.thumbnail}
                                            alt={event.title}
                                            className="w-full h-full object-cover"
                                          />
                                          {/* Time Watermark - Top Left */}
                                          <div className="absolute top-1 left-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                                            {event.time}
                                          </div>
                                          {/* Photo Count Watermark - Bottom Right */}
                                          <div className="absolute bottom-1 right-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                                            {event.photos}张
                                          </div>
                                        </div>

                                        {/* Event Title Only */}
                                        <h4 className="font-medium text-foreground text-sm line-clamp-1">
                                          {event.title}
                                        </h4>
                                      </CardContent>
                                    </Card>
                                  ))}
                                </div>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => toggleDay(dayKey)}
                                  className="w-full"
                                >
                                  <ChevronDown className="h-4 w-4 mr-2 rotate-180" />
                                  收起
                                </Button>
                              </div>
                            ) : (
                              // Horizontal Limited Layout
                              <div className="flex items-center gap-3">
                                <div className="flex gap-3 overflow-hidden">
                                  {visibleEvents.map((event, eventIndex) => (
                                    <Card
                                      key={eventIndex}
                                      className="flex-shrink-0 w-40 hover:shadow-md transition-shadow cursor-pointer"
                                      onClick={() =>
                                        navigate(
                                          `/event/${getEventId(event.title)}`,
                                        )
                                      }
                                    >
                                      <CardContent className="p-3">
                                        {/* Event Image with Watermarks */}
                                        <div className="relative w-full h-20 rounded-lg overflow-hidden mb-2">
                                          <img
                                            src={event.thumbnail}
                                            alt={event.title}
                                            className="w-full h-full object-cover"
                                          />
                                          {/* Time Watermark - Top Left */}
                                          <div className="absolute top-1 left-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                                            {event.time}
                                          </div>
                                          {/* Photo Count Watermark - Bottom Right */}
                                          <div className="absolute bottom-1 right-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                                            {event.photos}张
                                          </div>
                                        </div>

                                        {/* Event Title Only */}
                                        <h4 className="font-medium text-foreground text-sm line-clamp-1">
                                          {event.title}
                                        </h4>
                                      </CardContent>
                                    </Card>
                                  ))}
                                </div>
                                {hasMoreEvents && (
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => toggleDay(dayKey)}
                                    className="flex-shrink-0"
                                  >
                                    <ChevronDown className="h-4 w-4" />
                                  </Button>
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}

        {/* Load More */}
        <div className="text-center py-8">
          <Button variant="outline">加载更多回忆</Button>
        </div>
      </div>

      <BottomNavigation />
    </div>
  );
}
